package com.dotstone.chipism.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.dotstone.chipism.R;
import com.dotstone.chipism.util.CancelException;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.BadgeView;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class SettingActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private RelativeLayout mFeedbackR;
	private RelativeLayout mSystemInfoR;
	private RelativeLayout mSysLanuageR;
	private RelativeLayout mAboutUsR;
	private RelativeLayout mDemoR;
	private RelativeLayout mUpdateR;
	private BadgeView badgeView;
	private int localVersion;
	private int latestVersion;
	private NormalDialog mNormalDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private ProgressDialog pd;
	private boolean downloading = false;
	protected boolean cancelDownload;
	private AlertDialog dialog_download;
	protected int lastProgress;
	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.feedback_r:
			 Intent intent = new
			 Intent(SettingActivity.this,FeedbackActivity.class);
			 startActivity(intent);
			//ToastShow.Show(getApplicationContext(), "尚待完善");
			break;
		case R.id.system_info_r:
			ToastShow.Show(getApplicationContext(), "尚待完善");
			break;
		case R.id.lanuage_r:
			ToastShow.Show(getApplicationContext(), "尚待完善");
			break;
		case R.id.about_r:
			Intent intent1 = new Intent(SettingActivity.this, AboutUsActivity.class);
			startActivity(intent1);
			// ToastShow.Show(getApplicationContext(), "尚待完善");
			break;
		case R.id.demo_r:
			 Intent intent2 = new
			 Intent(SettingActivity.this,DemoActivity.class);
			 startActivity(intent2);
			//ToastShow.Show(getApplicationContext(), "xxx");
			break;
		case R.id.update_r:
			Intent intent22 = new Intent(SettingActivity.this,VersionActivity.class);
			startActivity(intent22);
		/*	// 判断当前软件版本
			// 获取系统版本
			Log.i("wmy", "latestVersion = "+latestVersion+" localVersion = "+localVersion);
			if (latestVersion <= localVersion) {
				ToastShow.Show(getApplicationContext(), "当前版本已是最新");
				return;
			}
			if (Build.VERSION.SDK_INT >= 23) {
				if (ContextCompat.checkSelfPermission(getApplicationContext(),
						Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
					boolean should = checkShould();
					if (should) {
						askPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
					} else {
						ActivityCompat.requestPermissions(SettingActivity.this, new String[] {
								Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE },
								0);
					}
				} else {
					downloadNewVersion(SocketManager.getInstance().downloadUrl);
				}
			} else {
				downloadNewVersion(SocketManager.getInstance().downloadUrl);
			}*/
			break;

		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case 9:
				downloading = false;
				pd.dismiss();
				ToastShow.Show(SettingActivity.this, "下载完成");
				// 下载完成后安装
				String savedFilePath = (String) msg.obj;
				Log.i("wmy", "下载完毕" + savedFilePath);
				Intent intent = new Intent();
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
					// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					intent.setAction(Intent.ACTION_VIEW);
					Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),
							"com.dotstone.chipism.fileprovider", new File(savedFilePath));
					intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
				} else {
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setAction(Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(new File(savedFilePath)),
							"application/vnd.android.package-archive");
				}
				startActivity(intent);
				break;
			case 10:
				pd.setProgress(msg.arg1);
				break;
			default:
				break;
			}
		}
	};

	protected void downloadNewVersion(final String urlString) {
		downloading = true;
		pd = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
		pd.setMessage(getString(R.string.downloading));
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setCancelable(false);// android 高版本对话框点击消失
		pd.show();
		pd.setProgress(0);
		pd.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface arg0) {
				cancelDownload = true;
			}
		});

		new Thread() {

			public void run() {
				try {
					InputStream input = null;
					HttpURLConnection urlConn = null;
					URL url = new URL(urlString);
					urlConn = (HttpURLConnection) url.openConnection();
					urlConn.setRequestProperty("Accept-Encoding", "identity");
					urlConn.setReadTimeout(10000);
					urlConn.setConnectTimeout(10000);
					input = urlConn.getInputStream();
					int total = urlConn.getContentLength();
					File file = null;
					OutputStream output = null;
					if (!new File(android.os.Environment.getExternalStorageDirectory().getPath() + "/cache").exists()) {
						new File(android.os.Environment.getExternalStorageDirectory().getPath() + "/cache").mkdirs();
					}
					// String savedFilePath =
					// android.os.Environment.getRootDirectory().getPath()
					// + "/cache/xintek.apk";
					String savedFilePath = android.os.Environment.getExternalStorageDirectory().getPath()
							+ "/cache/xintek.apk";
					file = new File(savedFilePath);
					output = new FileOutputStream(file);
					byte[] buffer = new byte[1024];
					int temp = 0;
					int read = 0;
					while ((temp = input.read(buffer)) != -1) {
						if (cancelDownload) {
							throw new CancelException();
						}
						output.write(buffer, 0, temp);
						read += temp;
						float progress = ((float) read) / total;
						int progress_int = (int) (progress * 100);
						if (lastProgress != progress_int) {
							lastProgress = progress_int;
							Message msg = new Message();
							msg.what = 10;// downloading
							msg.arg1 = progress_int;
							mHandler.sendMessage(msg);
						} else {
							// do not send msg
						}
					}
					output.flush();
					output.close();
					input.close();
					Message msg = new Message();
					msg.what = 9;
					msg.obj = savedFilePath;
					mHandler.sendMessage(msg);
				} catch (CancelException e) {
					Log.e("wmy", "取消下载啦");
					cancelDownload = false;
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(5);
				}
			};
		}.start();
	}

	@SuppressLint("NewApi")
	private boolean checkShould() {
		if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
			Log.e("wmy", "曾被设置永不提示");
			return true;
		} else {
			Log.e("wmy", "未曾设置永不提示");
			return false;
		}
	}

	private void askPermission(String permission) {
		String request = "";
		// if (permission.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
		request = "储存权限被禁止，是否前往设置界面开启？";
		// }
		mNormalDialog = new NormalDialog(SettingActivity.this);
		mNormalDialog.content(request).style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				Intent localIntent = new Intent();
				localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
				localIntent.setData(Uri.fromParts("package", SettingActivity.this.getPackageName(), null));
				startActivity(localIntent);
			}
		});
	}
	
	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		// Log.e("wmy", "调用权限" + requestCode + " " + permissions[0] + " " +
		// permissions[1] + " " + grantResults[0] + " "
		// + grantResults[1]);
		if (SocketManager.getInstance().downloadUrl != null && permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)
				&& grantResults[0] == 0) {
			downloadNewVersion(SocketManager.getInstance().downloadUrl);
		} else {
			ToastShow.Show(getApplicationContext(), "权限已被禁止");
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_setting;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mFeedbackR = $(R.id.feedback_r);
		mSystemInfoR = $(R.id.system_info_r);
		mSysLanuageR = $(R.id.lanuage_r);
		mAboutUsR = $(R.id.about_r);
		mDemoR = $(R.id.demo_r);
		mUpdateR = $(R.id.update_r);
		badgeView = new BadgeView(this);
		boolVersion();
		mBackL.setOnClickListener(this);
		mFeedbackR.setOnClickListener(this);
		mSystemInfoR.setOnClickListener(this);
		mSysLanuageR.setOnClickListener(this);
		mAboutUsR.setOnClickListener(this);
		mDemoR.setOnClickListener(this);
		mUpdateR.setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initData();
	}

	private void initData() {
		latestVersion = SocketManager.getInstance().getV();
		localVersion = SocketManager.getInstance().getAppVersion();
		Log.i("wmy", "latestVersion" + latestVersion + " localVersion = " + localVersion);
		if (latestVersion > localVersion) {
			badgeView = new BadgeView(this, mUpdateR);
			badgeView.setText("New");
			badgeView.setTextColor(Color.WHITE);
			badgeView.show();
		}
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

}
